/**
 *-----------------------------------------------------------------------------
 * @ Copyright(c) 2015~2020  NARI南瑞集团
 *-----------------------------------------------------------------------------
 * FILE  NAME             : StringUtils.java
 * DESCRIPTION            : 字符串工具类
 * PRINCIPAL AUTHOR       : wenpf
 * SYSTEM NAME            : 项目管理平台
 * MODULE NAME            : 公用方法
 * LANGUAGE               : Java
 * DATE OF FIRST RELEASE  :
 *-----------------------------------------------------------------------------
 * @ Created on 2015年9月16日
 * @ Release 1.0.0.0
 * @ Version 1.0
 * ----------------------------------------------------------------------------
 * Date             Author                  Version       Description
 * ----------------------------------------------------------------------------
 * 2015年9月16日    wenpf                   1.0           Initial Create
 * ----------------------------------------------------------------------------
 */
package com.example.fangyimanagement.core;

import org.apache.commons.lang3.ArrayUtils;
import org.slf4j.helpers.MessageFormatter;

import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 字符串工具类
 * @author wenpf
 */
public class StringUtils extends org.apache.commons.lang3.StringUtils {

    public static String makeInConditionStr(Collection<String> items) {
        return makeInConditionStr(items, ",");
    }

    public static String makeInConditionStr(Collection<String> items, String split) {
        StringBuilder builder = new StringBuilder();
        int index = 0;
        for (String str : items) {
            if (str != null) {
                str = str.replace("'", "''");
            }
            builder.append("'").append(str).append("'");
            if (index != (items.size() - 1)) {
                builder.append(split);
            }
            index++;
        }
        return builder.toString();
    }

    public static String makeInConditionStrPaddingZero(String str,
            String split) {
        String retVal = str;
        if (isNotEmpty(str)) {
            String[] arr = str.split(split);
            StringBuffer buf = new StringBuffer();
            for (int index = 0; index < arr.length; index++) {
                buf.append("'0").append(arr[index]).append("'");
                if (index == (arr.length - 1)) {

                } else {
                    buf.append(",");
                }
            }
            retVal = buf.toString();
        }
        return retVal;
    }

    public static String makeInConditionStr(String str, String split) {
        String retVal = str;
        if (isNotEmpty(str)) {
            String[] arr = str.split(split);
            StringBuilder buf = new StringBuilder();
            for (int index = 0; index < arr.length; index++) {
                buf.append("'").append(arr[index]).append("'");
                if (index != (arr.length - 1)) {
                    buf.append(",");
                }
            }
            retVal = buf.toString();
        }
        return retVal;
    }

    private static DecimalFormat decimalFmt = new DecimalFormat("#.##");

    public static String fmtBigDecimalWith2Point(BigDecimal num) {
        return decimalFmt.format(num);
    }

    public String nvl(String str, String repStr) {
        if (isEmpty(str)) {
            return repStr;
        }
        return str;
    }

    public static String toStringWithDefault(Object obj, String defaultVal) {
        String retVal = null;
        if (null != obj) {
            retVal = obj.toString();
        }
        if (isEmpty(retVal)) {
            retVal = defaultVal;
        }
        return retVal;
    }

    /**
     * 对象转 String
     * @param obj Object
     * @return String
     */
    public static String toString(Object obj) {
        if (null == obj) {
            return "";
        }
        return obj.toString();
    }

    /**
     * 判断字符串是否为null或者空或者只含空白符
     * @param str 待判断字符串
     * @return
     */
    public static boolean isBlank(String str) {
        int strLen;
        if (null == str || 0 == (strLen = str.length())) {
            return true;
        } else {
            for (int i = 0; i < strLen; i++) {
                if (!Character.isWhitespace(str.charAt(i))) {
                    return false;
                }
            }
        }
        return true;
    }

    /**
     * 判断字符串是否不为空串
     * @param str 待判断字符串
     * @return 空串，真；非空串，假；
     */
    public static boolean isNotBlank(String str) {
        return !isBlank(str);
    }

    /**
     * 判断字符串是否为null或者空
     *
     * @param str
     * @return
     */
    public static boolean isEmpty(String str) {
        return null == str || "null".equals(str) || 0 == str.length();
    }

    public static String replaceBlank(String str) {
        String dest = "";
        if (isNotEmpty(str)) {
            Pattern p = Pattern.compile("\\s*|\t|\r|\n");
            Matcher m = p.matcher(str);
            dest = m.replaceAll("");
        }
        return dest;
    }

    /**
     * 判断字符串是否不为空串
     * @param str 待判断字符串
     * @return 空串，真；非空串，假；
     */
    public static boolean isNotEmpty(String str) {
        return !isEmpty(str);
    }

    /**
     * 将整型字符串转化为整型
     *
     * @param value
     *            整型字符串
     * @return 整型数字，如果字符串非法，抛出异常
     */
    public static int toInteger(Object value) {
        return Integer.valueOf(StringUtils.toString(value));
    }

    /**
     * 转换成int[]数组
     * @param arr
     * @return
     */
    public static final int[] integerToInt(Integer[] arr) {
        int[] array = new int[arr.length];
        for (int i = 0; i < arr.length; i++) {
            array[i] = (int) arr[i];
        }
        return array;
    }

    /**
     * 是否是数字
     * @param value
     * @return
     */
    public static boolean isInteger(String value) {
        Pattern pattern = Pattern.compile("[0-9]*");
        return pattern.matcher(value).matches();
    }

    /**
     * 是否是年月2017.7
     * @param value
     * @return
     */
    public static boolean isYearMonth(String value) {
        Pattern pattern = Pattern.compile("[0-9]{4}年[1-9]([0-2])?月");
        return pattern.matcher(value).matches();
    }

    /**
     * 年月2017年7月 转 数字
     * @param yearMonth
     * @return
     */
    public static String yearMonthToInt(String yearMonth) {
        String[] yms = yearMonth.split("年");
        String year = "";
        if (yms != null && yms.length == 2) {
            int m = Integer.valueOf(yms[1].replaceAll("月", ""));
            String mm = (m < 10) ? ("0" + m) : "" + m;
            year = yms[0] + mm;
        }
        return year;
    }

    /**
     * 年月2017年7月
     * @param yearMonth
     * @return
     */
    public static String getYear(String yearMonth) {
        String[] yms = yearMonth.split("年");
        String year = "";
        if (yms != null && yms.length == 2) {
            year = yms[0];
        }
        return year;
    }

    /**
     * 年月2017年7月
     * @param yearMonth
     * @return
     */
    public static String getMonth(String yearMonth) {
        String[] yms = yearMonth.split("年");
        String year = "";
        if (yms != null && yms.length == 2) {
            int m = Integer.valueOf(yms[1].replaceAll("月", ""));
            String mm = (m < 10) ? ("0" + m) : "" + m;
            year = mm;
        }
        return year;
    }

    public static String subStrYearMonth(String yyyy_MM_dd) {
        if ( StringUtils.isNotEmpty(yyyy_MM_dd) && yyyy_MM_dd.length() >= 8) {
            return yyyy_MM_dd.substring(0, 8);
        }
        return yyyy_MM_dd;
    }

    public static final String EXP_ASSIGNER = "(#(\\d*)#)";

    public static Set<String> matcherStringByExp(String str, String exp) {
        Set<String> set = new HashSet<String>();
        Pattern p2 = Pattern.compile(exp); // "(\\d(\\d*))"
        Matcher m = p2.matcher(str);
        while (m.find()) {
            set.add(m.group(0));
            System.out.println(m.group(0));
        }
        return set;
    }

    /**
     * 将Set中的元素拼接成字符串
     * @param set
     * @param split
     * @return
     */
    public static <T> String set2String(Set<T> set, String split) {
        StringBuffer buf = new StringBuffer();
        int index = 0;
        for (T item : set) {
            if (index++ == 0) {
                buf.append(item.toString());
            } else {
                buf.append(split);
                buf.append(item.toString());
            }
        }
        return buf.toString();
    }

    private static Pattern linePattern = Pattern.compile("_(\\w)");

    public static String uperFirstLetter(String str) {
        char[] cs = str.toCharArray();
        cs[0] -= 32;
        return String.valueOf(cs);
    }

    public static String lineToHump(String str) {
        str = str.toLowerCase();
        Matcher matcher = linePattern.matcher(str);
        StringBuffer sb = new StringBuffer();
        while (matcher.find()) {
            matcher.appendReplacement(sb, matcher.group(1).toUpperCase());
        }
        matcher.appendTail(sb);
        return sb.toString();
    }

    public static void main(String[] args) {
        String test = "#1111#,#2222#,#3333#";
        matcherStringByExp(test, EXP_ASSIGNER);
    }

    /**
     * 判断字符串是否整数或者小数
     * @param str 待判断字符串
     * @return
     */
    public static boolean isNumber(String str) {
        if (null == str || "".equals(str) || 0 == str.length()) {
            return false;
        }
        boolean int_flag = Pattern.compile("^-?[1-9]\\d*$").matcher(str).find();
        boolean double_flag = Pattern
                .compile("^-?([1-9]\\d*\\.\\d*|0\\.\\d*[1-9]\\d*|0?\\.0+|0)$")
                .matcher(str).find();
        if (int_flag) {
            return true;
        } else if (double_flag) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 提供类似于slf4j的日志+参数自动合并的工具
     * @param message
     * @param params
     * @return
     */
    public static String format(String message, Object... params) {
        if (ArrayUtils.isEmpty(params)) {
            return message;
        }
        return MessageFormatter.arrayFormat(message, params).getMessage();
    }

    public static int countPrefix(String s, String prefix) {
        String current = s;
        int count = 0;
        while ((current.startsWith(prefix))) {
            count++;
            current = current.substring(prefix.length());
        }
        return count;
    }

    public static String wrap(final String str, final String wrapWith) {
        if (isEmpty(str) || isEmpty(wrapWith)) {
            return str;
        }
        return wrapWith.concat(str).concat(wrapWith);
    }

    public static String repeat(String value, int count, String separator) {
        List<String> values = new ArrayList<String>();
        for (int i = 0; i < count; i++) {
            values.add(value);
        }
        return StringUtils.join(values, separator);
    }

    public static boolean hasText(String text) {
        return org.springframework.util.StringUtils.hasText(text);
    }

    /**
     * 驼峰转下划线小写
     * @param input
     * @return
     */
    public static String camelToUnderlineLowerCase(CharSequence input) {
        if (input == null) return null; // garbage in, garbage out
        int length = input.length();
        StringBuilder result = new StringBuilder(length * 2);
        int resultLength = 0;
        boolean wasPrevTranslated = false;
        for (int i = 0; i < length; i++) {
            char c = input.charAt(i);
            if (i > 0 || c != '_') // skip first starting underscore
            {
                if (Character.isUpperCase(c)) {
                    if (!wasPrevTranslated && resultLength > 0 && result.charAt(resultLength - 1) != '_') {
                        result.append('_');
                        resultLength++;
                    }
                    c = Character.toLowerCase(c);
                    wasPrevTranslated = true;
                } else {
                    wasPrevTranslated = false;
                }
                result.append(c);
                resultLength++;
            }
        }
        return resultLength > 0 ? result.toString() : null;
    }

    public static String trimToEmpty(Object o) {
        return org.apache.commons.lang3.StringUtils.trimToEmpty(Objects.toString(o, ""));
    }

    public static String trimToNull(Object o) {
        return org.apache.commons.lang3.StringUtils.trimToNull(Objects.toString(o, null));
    }

    /**
     * 将["123", "456"]格式的参数变成形如'123','456'的字符串
     * @param list
     * @return
     */
    public static String joinForIn(List<?> list) {
        StringBuilder builder = new StringBuilder();
        for (Object o : list) {
            String item = Objects.toString(o, null);
            if (item == null) {
                continue;
            }
            builder.append(StringUtils.wrap(item.replace("'", "''"), "'")).append(",");
        }
        if (builder.length() > 0) {
            builder.deleteCharAt(builder.length() -1);
        }
        return builder.toString();
    }

}
